package com.tsinghuabigdata.edu.ddmath.module.login.view;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.mobsandgeeks.saripaar.ValidationError;
import com.mobsandgeeks.saripaar.Validator;
import com.mobsandgeeks.saripaar.annotation.Length;
import com.mobsandgeeks.saripaar.annotation.NotEmpty;
import com.tsinghuabigdata.edu.commons.http.HttpRequestException;
import com.tsinghuabigdata.edu.ddmath.MVPModel.RequestListener;
import com.tsinghuabigdata.edu.ddmath.R;
import com.tsinghuabigdata.edu.ddmath.activity.RoboForToolBarActivity;
import com.tsinghuabigdata.edu.ddmath.bean.LoginInfo;
import com.tsinghuabigdata.edu.ddmath.commons.http.HttpResponse;
import com.tsinghuabigdata.edu.ddmath.commons.http.InformMapping;
import com.tsinghuabigdata.edu.ddmath.commons.http.ResponseCode;
import com.tsinghuabigdata.edu.ddmath.constant.AppConst;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginModel;
import com.tsinghuabigdata.edu.ddmath.module.login.LoginSuccessHandler;
import com.tsinghuabigdata.edu.ddmath.util.AccountUtils;
import com.tsinghuabigdata.edu.ddmath.util.AlertManager;
import com.tsinghuabigdata.edu.ddmath.util.AppUtils;
import com.tsinghuabigdata.edu.ddmath.util.GlobalData;
import com.tsinghuabigdata.edu.ddmath.util.KeyboardUtil;
import com.tsinghuabigdata.edu.ddmath.util.PicassoUtil;
import com.tsinghuabigdata.edu.ddmath.util.PreferencesUtils;
import com.tsinghuabigdata.edu.ddmath.view.MyProgressDialog;
import com.tsinghuabigdata.edu.utils.NetworkUtils;

import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;


/**
 * login
 * Created by Administrator on 2016/12/14.
 */

public class LoginActivity extends RoboForToolBarActivity implements View.OnClickListener {
    private static final String TAG = "RegisterFragment";
    private View root;

    @ViewInject(R.id.bt_enterdoudou)
    private Button btEnterdoudou;
    @Length(trim = true, max = 16, message = "帐号不合法", sequence = 2)
    @NotEmpty(trim = true, message = "帐号不能为空", sequence = 1)
    @ViewInject(R.id.et_phone)
    private EditText etPhone;
    @Length(trim = true, max = 20, min = 6, message = "密码最少6位，请重新输入", sequence = 2)
    @NotEmpty(trim = true, message = "密码不能为空", sequence = 1)
    @ViewInject(R.id.et_passwd)
    private EditText etPasswd;

    @ViewInject(R.id.tv_forget_pass)
    private TextView tvForgetPass;

    private Validator mValidator;

    private MyProgressDialog progressDialog;
    private Context context;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        x.view().inject(this);

        initView();
        initData();

        initValidator();
    }

    private void initView() {
        setLeftTitle("返回");
        setTitle("登录");
        setBarTextcolor(R.color.white);
        setUserBarBackgroud(true);

        progressDialog = new MyProgressDialog(context);

        //记忆登录名
        etPhone.setText(PreferencesUtils.getString(context, AppConst.LOGIN_NAME, ""));

        //listener
        btEnterdoudou.setOnClickListener(this);
        tvForgetPass.setOnClickListener(this);

    }

    @Override
    public void onLeftClick() {
        super.onLeftClick();
        finish();
    }

    private void initValidator() {
        mValidator = new Validator(this);
        mValidator.setValidationListener(new Validator.ValidationListener() {
            @Override
            public void onValidationSucceeded() {
                KeyboardUtil.hidInput((Activity) context);
//                if (!ValidatorUtils.validateMobile(etPhone.getText().toString().trim())) {
//                    etPhone.setError("请输入正确的手机号");
//                    return;
//                }
                login();
            }

            @Override
            public void onValidationFailed(List<ValidationError> errors) {
                for (ValidationError error : errors) {
                    ((EditText) error.getView()).setError(error.getFailedRules().get(0).getMessage(context));
                }
            }
        });
    }

    private void login() {
        progressDialog.setMessage("正在登录...");
        progressDialog.show();

        final String loginName = etPhone.getText().toString().trim();
        final String passwd = etPasswd.getText().toString().trim();
        new LoginModel().login(context, loginName, passwd, new RequestListener<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                progressDialog.dismiss();
                if (loginInfo == null) {
                    AlertManager.toast(context, "用户名或密码错误");
                } else {
                    PicassoUtil.init();

                    String phone = AccountUtils.getUserdetailInfo().getPhone();
                    LoginSuccessHandler.loginSuccessHandler(context, loginName, passwd);
                    finish();
                    goUsercenter();
                    GlobalData.setLoginChange(true);
                    if (TextUtils.isEmpty(phone)) {
                        //没有绑定手机号
                        goActivity(BindMobileActivity.class);
                    }
                }
            }

            @Override
            public void onFail(HttpResponse response, Exception ex) {
                progressDialog.dismiss();
                if (AppUtils.isNoNetwork() || NetworkUtils.isNoConnection(ex)) {
                    AlertManager.toast(context, getString(R.string.no_connection));
                } else if (response.getCode() != ResponseCode._10000 && response.getInform() != null) {
                    if (response.getInform().contains("student is null")) {
                        AlertManager.toast(context, "获取个人信息失败");
                    } else {
                        AlertManager.toast(context, InformMapping.getInstance().get(response.getInform()));
                    }
                } else if (ex instanceof HttpRequestException) {
                    if (((HttpRequestException) ex).getRequest().getStatusCode() == 412 || ((HttpRequestException) ex).getRequest().getStatusCode() == 401) {
                        AlertManager.toast(context, "用户名或密码错误");
                    } else {
                        AlertManager.toast(context, getString(R.string.server_error));
                    }
                } else {
                    AlertManager.toast(context, getString(R.string.server_error));
                }
            }
        });
    }


    private void initData() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_enterdoudou:
                mValidator.validate();
                break;
            case R.id.tv_forget_pass:
                goActivity(RecoverPassActivity.class);
                break;
        }
    }

}
